package controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.w3c.dom.NodeList;

import model.BounBookUser;
import model.Feed;
import model.Notes;
import model.ProfileFieldDefinition;
import model.UserProfile;

import util.HibernateUtil;
import util.Tagging;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class ProfileController extends ActionSupport implements ServletRequestAware{

	private static final long serialVersionUID = 1L;
	
	public String name;
	
	public List<Feed> feedList = new ArrayList<Feed>();
	public List<Notes> noteList = new ArrayList<Notes>();
	
	public Feed feed = new Feed();;
	
	public List<ProfileFieldDefinition> fields = new ArrayList<ProfileFieldDefinition>();
	public List<UserProfile> userProfileList = new ArrayList<UserProfile>();
	public Hashtable<Integer,UserProfile> somedic = new Hashtable<Integer,UserProfile>();
	public int userId;
	public Date d;
	public HttpServletRequest request;
	public final String seperator = "\\|";
	public String error = "";
	
	public BounBookUser bookUser;
	
	//	0	: View
	//	1	: Update Success
	// 	2	: Update Fail (Required Area Missing)
	//	3	: Update Fail (Wrong option)
	//	4	: Digimons ate the database!...

	@Override
	public String execute() throws Exception {
		//fillers
		if (name != null)
		{
			Dictionary<String, Object> dictionary = new Hashtable<String, Object>();
			dictionary.put("name", name.split(" ")[0]);
			dictionary.put("lastname", name.split(" ")[1]);
			this.setUserId(((BounBookUser) HibernateUtil.list("from BounBookUser where name = :name AND lastname = :lastname", dictionary).get(0)).getId());
		}
		else if (userId == 0)
		{
			Map<String, Object> session = ActionContext.getContext().getSession();
			this.setUserId(Integer.valueOf(session.get("userId").toString()));
		}
		
		bookUser = HibernateUtil.get(BounBookUser.class, this.getUserId()); 
			
		d  = (Date) new SimpleDateFormat("MM.dd.yy").parse("01.29.02");
		//end-fillers
		this.somedic = this.getFilledList(this.userId);
		
		Dictionary<String, Object> dictionary = new Hashtable<String, Object>();
		
		dictionary.put("userId", userId);
		
		feedList = HibernateUtil.list("from Feed WHERE userId = :userId  ORDER BY ID Desc", dictionary);		
		noteList = HibernateUtil.list("from Notes WHERE userId = :userId  ORDER BY ID Desc", dictionary);
		
		Tagging.Tag(feedList);
		
		return SUCCESS;
	}
	@SuppressWarnings("unchecked")
	public String updateProfile() throws Exception{
		//fillers
		if (userId == 0)
		{
			Map<String, Object> session = ActionContext.getContext().getSession();
			this.setUserId(Integer.valueOf(session.get("userId").toString()));
		}
		//end-fillers
		fields = this.getFields();
		//check for Database correctness; are all request(counts) are found in database?
		Hashtable<String, ProfileFieldDefinition> fieldsList = new Hashtable<String, ProfileFieldDefinition>();
		for(int a=0;a<fields.size();a++){
			if(request.getParameter(String.valueOf(a)) != null   && fields.get(a).getIsRequired())
				if(request.getParameter(String.valueOf(a)).replace(" ","") == ""){
					error = "Missing Fields";
				}
			fieldsList.put(String.valueOf(fields.get(a).getId()), fields.get(a));
			//userProfileList.
		}
		for(Enumeration e =  request.getParameterNames(); e.hasMoreElements();){
			Object o = e.nextElement();
			if(Pattern.matches("\\d*",o.toString())){
				/*
				if(!fieldsList.containsKey("o")){
					error = "Form information not valid... Refresh needed";
				}
				fixmeh */
				UserProfile u = new UserProfile();
				String[] values = request.getParameterValues(o.toString());
				String toBeWritten = "";
				for(int a=0; a<values.length;a++){
					if(a>0)
						toBeWritten += this.seperator;
					toBeWritten += values[a];
				}
				u.setInputValue(toBeWritten);
				u.setUserId(this.userId);
				u.setProfileFieldDefinitionId(new Integer(o.toString()));
				u.setPrivate(request.getParameter("c"+o.toString()) == null ? false: true);
				this.userProfileList.add(u);
			}
		}
		bookUser = HibernateUtil.get(BounBookUser.class, this.getUserId());
		//delete from database the existing information
		Dictionary<String,Object> d = new Hashtable<String,Object>();
		d.put("id", userId);
		List<UserProfile> l = HibernateUtil.list("from UserProfile as u where u.userId = :id",d);
		for(int a=0;a<l.size();a++){
			HibernateUtil.delete(UserProfile.class, l.get(a).getId());
		}
		for(int a=0;a<userProfileList.size();a++){
			HibernateUtil.insert(userProfileList.get(a));
		}
		this.somedic = this.getFilledList(this.userId);
		Dictionary<String, Object> dictionary = new Hashtable<String, Object>();
		
		dictionary.put("userId", userId);
		
		feedList = HibernateUtil.list("from Feed WHERE userId = :userId  ORDER BY ID Desc", dictionary);		
		noteList = HibernateUtil.list("from Notes WHERE userId = :userId  ORDER BY ID Desc", dictionary);
		
		Tagging.Tag(feedList);
		return SUCCESS;
	}
	public List<ProfileFieldDefinition> getFields() throws Exception{
		return HibernateUtil.list("from ProfileFieldDefinition");		
	}
	
	public Hashtable<Integer,UserProfile> getFilledList(int id) throws Exception{
		this.fields = this.getFields();
		Hashtable<Integer,UserProfile> somedic = new Hashtable<Integer, UserProfile>();
		for(int a=0;a<this.fields.size();a++){
			String query = "from UserProfile as u where u.userId = "+id+" and u.profileFieldDefinitionId = "+((ProfileFieldDefinition)this.fields.get(a)).getId()+"";
			List<UserProfile> l = HibernateUtil.list(query);
			if(l.size()==0){
				UserProfile u = new UserProfile();
				u.setProfileFieldDefinitionId(new Integer(this.fields.get(a).getProfileFieldDefinitionType()));
				u.setInputValue(this.fields.get(a).getDefaultValue());
				u.setPrivate(false);
				u.setUserId(id);
				somedic.put(fields.get(a).getId(),u);
			}else{
				somedic.put(fields.get(a).getId(),l.get(0));
			}
		}
		return somedic;
	}
	
	public String updateStatus() {
		if (userId == 0)
		{
			Map<String, Object> session = ActionContext.getContext().getSession();
			this.setUserId(Integer.valueOf(session.get("userId").toString()));
		}
		
		feed.setCreated(new Date());
		feed.setUserId(userId);
		HibernateUtil.insert(feed);
		Dictionary<String, Object> dictionary = new Hashtable<String, Object>();
		
		dictionary.put("userId", userId);
		
		feedList = HibernateUtil.list("from Feed WHERE userId = :userId ORDER BY ID Desc", dictionary);
		
		Tagging.Tag(feedList);
		bookUser = HibernateUtil.get(BounBookUser.class, this.getUserId());
		return SUCCESS;
	}
	public void setServletRequest(HttpServletRequest request){
		this.request = request;
	}

	public HttpServletRequest getServletRequest(){
		return request;
	}
	public int getUserId(){
		return this.userId;
	}
	public void setUserId(int userId){
		this.userId = userId;
	}
}